#!/bin/bash

set -e

CHANGED=false

cd $(dirname $0)/..

# Rebuild the Ohm grammar if necessary.
if [ src/ohm-grammar.ohm -nt dist/ohm-grammar.js ]; then
  src/ohm-cmd.js src/ohm-grammar.ohm > dist/ohm-grammar.js.new
  mv -f dist/ohm-grammar.js.new dist/ohm-grammar.js
  CHANGED=true
fi

# Rebuild the built-in rules grammar if necessary.
if [ "$CHANGED" == "true" ] || [ src/built-in-rules.ohm -nt dist/built-in-rules.js ]; then
  src/ohm-cmd.js src/built-in-rules.ohm > dist/built-in-rules.js.new
  mv -f dist/built-in-rules.js.new dist/built-in-rules.js
  CHANGED=true
fi

# Rebuild the operations and attributes grammar if necessary.
if [ "$CHANGED" == "true" ] || [ src/operations-and-attributes.ohm -nt dist/operations-and-attributes.js ]; then
  src/ohm-cmd.js src/operations-and-attributes.ohm > dist/operations-and-attributes.js.new
  mv -f dist/operations-and-attributes.js.new dist/operations-and-attributes.js
  CHANGED=true
fi

# Run the tests if one of the files changed and the `--test` argument is set.
if [ "$CHANGED" == "true" ] && [ "$1" == "--test" ]; then
  pnpm test --silent
fi

echo 'Bootstrap complete.'
